package com.xuecheng.learning.service.Impl;

import com.alibaba.fastjson.JSON;
import com.xuecheng.base.model.RestResponse;
import com.xuecheng.content.model.po.CoursePublish;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.learning.feignclient.ContentServiceClient;
import com.xuecheng.learning.feignclient.MediaServiceClient;
import com.xuecheng.learning.model.dto.XcCourseTablesDto;
import com.xuecheng.learning.service.LearningService;
import com.xuecheng.learning.service.MyCourseTablesService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class LearningServiceImpl implements LearningService {
    @Autowired
    ContentServiceClient contentServiceClient;
    @Autowired
    MediaServiceClient mediaServiceClient;
    @Autowired
    MyCourseTablesService myCourseTablesService;
    @Override
    public RestResponse<String> getVideo(String userId, Long courseId, Long teachplanId, String mediaId) {
        //查询该课程
        CoursePublish coursepublish = contentServiceClient.getCoursepublish(courseId);
        if (coursepublish==null){
            return RestResponse.validfail("该课程不存在");
        }
        //获取该课程的课程计划
        Teachplan teachplan = contentServiceClient.getTeachplan(teachplanId);
        String isPreview = teachplan.getIsPreview();
        if ("1".equals(isPreview)){//支持试学
                return mediaServiceClient.getPlayUrlByMediaId(mediaId);
        }
        //判断用户是否登录
        if (StringUtils.isNotEmpty(userId)){//已经登录
            //判断是否有学习资格
            XcCourseTablesDto learningStatus = myCourseTablesService.getLearningStatus(userId, courseId);
            String learnStatus = learningStatus.getLearnStatus();
            if ("702002".equals(learnStatus)){
                return RestResponse.validfail("没有选课或者选课后没有支付");
            }
            if ("702003".equals(learnStatus)){
                return RestResponse.validfail("已过期需要申请续约重新支付");
            }
            if ("702001".equals(learnStatus)){
                RestResponse<String> playUrlByMediaId = mediaServiceClient.getPlayUrlByMediaId(mediaId);
                return playUrlByMediaId;
            }
        }
        //没有登录的情况下，查看课程收费情况
        String charge = coursepublish.getCharge();
        if ("201000".equals(charge)){
            return mediaServiceClient.getPlayUrlByMediaId(mediaId);
        }
        return RestResponse.validfail("没有登录或者登录后未成功选课");
    }
}
